//导入包
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';

//应用入口
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //应用名称
      title: 'Flutter Demo',
      //主题
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      //应用首页路由
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  @override
  State<StatefulWidget> createState() {
    return _MyHomePageState();
  }
}


class _MyHomePageState extends State<MyHomePage> {

  ByteData? toByteData;
  Uint8List? dataTest;
  String status = "12";
  int uiImageWidth = 1;
  ImageProvider image = AssetImage("images/picture_7.png");

  List<Widget> list = <Widget>[];

  @override
  void initState() {
    super.initState();
  }

  Future<void> getDirectory() async {
    print("开始${DateTime.now().millisecondsSinceEpoch}");
    ui.Image uiImage = await loadImageByProvider(image!,context);
    print("ui.Image获取成功${DateTime.now().millisecondsSinceEpoch}");
    toByteData = await uiImage.toByteData(format: ui.ImageByteFormat.rawRgba);
    print("RBGA数组获取成功${DateTime.now().millisecondsSinceEpoch}");
    if(toByteData==null) return;
    status = "";
    List<Widget> listcache = [];
    int num = 0;
    uiImageWidth = uiImage.width;
    for(int i=0; i<uiImage.height; i++ ){
      for(int j=0; j<uiImage.width; j++ ){
        var number = (i*uiImage.height + j)*4;
        int a = toByteData?.getUint8(number+3)??0;
        int r = toByteData?.getUint8(number)??0;
        int g = toByteData?.getUint8(number+1)??0;
        int b = toByteData?.getUint8(number+2)??0;
        num++;
        print("获取元素颜色 $a == $r == $g == $b ${DateTime.now().millisecondsSinceEpoch}");
        setState(() {
          list.add(
            DecoratedBox(
              decoration: BoxDecoration(color: Color.fromARGB(a, r, g, b)),
            ),
          );
        });
      }
    }
    print("编码成功${DateTime.now().millisecondsSinceEpoch}");
    // setState(() {
    //   list = listcache;
    // });
  }

  static Future<ui.Image> loadImageByProvider(ImageProvider provider, BuildContext context) async {
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调

    late ImageStreamListener listener;
    ImageStream stream = provider.resolve(createLocalImageConfiguration(context)); //获取图片流
    listener = ImageStreamListener((ImageInfo frame, bool sync) {
      //监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
      stream.removeListener(listener); //移除监听
    });
    stream.addListener(listener); //添加监听
    return completer.future; //返回
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Center(
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              GridView.count(
                primary: false,
                crossAxisCount: uiImageWidth,
                children: list,
              ),
              Positioned(
                  bottom: 0,
                  child: Image(
                    image: image,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.width,
                    fit: BoxFit.fitWidth,
                  )
              ),
              OutlinedButton(
                  onPressed: (){
                    getDirectory();
                  },
                  child: Text("分解图片")
              ),
            ],
          )
      ),
    );
  }
}

